package com.example.test2.view;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.new6.R;
import com.example.test2.retrofit.RetClient;
import com.example.test2.entity.TranslationResponse;
import com.example.test2.service.TranslationService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TranslateActivity extends AppCompatActivity {
    private EditText sourceText;
    private TextView targetText;
    private Button translateButton;
    private TranslationService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_translate);

        sourceText = findViewById(R.id.source_text);
        targetText = findViewById(R.id.target_text);
        translateButton = findViewById(R.id.translate_button);

        // 注意：URL字符串应该以"/"结尾
        service = RetClient.getClient("https://api.oioweb.cn/").create(TranslationService.class);

        translateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String textToTranslate = sourceText.getText().toString().trim();
                if (!textToTranslate.isEmpty()) {
                    translateText(textToTranslate);
                } else {
                    targetText.setText("请输入要翻译的文本。");
                }
            }
        });
    }

    private void translateText(String sourceText) {
        if (sourceText.isEmpty()) {
            targetText.setText("sourceText不能为空。");
            return;
        }

        Call<TranslationResponse> call = service.translateText(sourceText);
        call.enqueue(new Callback<TranslationResponse>() {
            @Override
            public void onResponse(Call<TranslationResponse> call, Response<TranslationResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    TranslationResponse translationResponse = response.body();
                    if (translationResponse.getCode() == 200) {
                        targetText.setText(translationResponse.getResult().getTargetText());
                    } else {
                        targetText.setText("翻译错误: " + translationResponse.getMsg());
                    }
                } else {
                    targetText.setText("服务器错误: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<TranslationResponse> call, Throwable t) {
                // 在UI线程中更新文本视图
                runOnUiThread(() -> targetText.setText("连接错误: " + t.getMessage()));
            }
        });
    }
}